package com.banciyuan.bcywebview.biz.groupdetail;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.GroupApi;
import com.banciyuan.bcywebview.base.activity.BaseActivity;
import com.banciyuan.bcywebview.base.helper.ActionbarHelper;
import com.banciyuan.bcywebview.base.helper.LoadingHelper;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.myinterface.ActionInterface;
import com.banciyuan.bcywebview.biz.circles.relatedcircle.RelatedCircleAdapter;
import com.banciyuan.bcywebview.biz.circles.smooth.CircleSmoothActivity;
import com.banciyuan.bcywebview.biz.circles.smooth.CircleTagSmoothActivity;
import com.banciyuan.bcywebview.biz.event.EventDetailActivity;
import com.banciyuan.bcywebview.biz.groupdetail.info.EditTagActivity;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.OnErrorProxy;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import de.greenrobot.daoexample.model.TagDetail;
import de.greenrobot.daoexample.model.Team;

public class GroupTagInfoActivity extends BaseActivity implements View.OnClickListener, AdapterView.OnItemClickListener {
    private ActionbarHelper mActionbarHelper;
    private View mActionBarView;
    private RequestQueue mQueue;
    private String mGid = "";
    private ListView mListView;
    private ActionInterface getDataInterface;
    private Team team;
    private final int GO_EDIT_TAG = 2;
    private RelatedCircleAdapter mAdapter;
    private LoadingHelper mProgressbarHelper;
    private View rootView;
    private List<TagDetail> relaCircle = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        rootView = View.inflate(this, R.layout.activity_group_tag_list, null);
        setContentView(rootView);
        initArgs();
        initProgressbar();
        initActionbar();
        initUi();
        initAction();
        initData();
    }

    @Override
    protected void initArgs() {
        Intent intent = getIntent();
        if (intent != null) {
            mGid = intent.getStringExtra(gotoUtil.INTENT_VALUE_ONE);
        }
        getDataInterface = new ActionInterface() {
            @Override
            public void onNetError(String result) {
                if (null != mProgressbarHelper) {
                    mProgressbarHelper.onFailed();
                }
            }
        };
        mQueue = VolleyQueue.getRquest(getContext());
    }

    @Override
    protected void initProgressbar() {
        mProgressbarHelper = new LoadingHelper(rootView);
        mProgressbarHelper.setActionCallbacks(new LoadingHelper.OnProgressCallbacks() {
            @Override
            public void onActionClick(int id) {
                int state = mProgressbarHelper.getState();
                if (state == LoadingHelper.PROGRESS_STATE_NODATA)
                    return;
                mProgressbarHelper.onLoading();
                initData();
            }
        });
        mProgressbarHelper.onLoading();
    }

    @Override
    protected void initActionbar() {
        mActionBarView = findViewById(R.id.base_action_bar);
        mActionbarHelper = new ActionbarHelper(this, mActionBarView);
        mActionbarHelper.setTitle(getString(R.string.releated_work));
        mActionbarHelper.setActionCallbacks(new ActionbarHelper.OnActionCallbacks() {
            @Override
            public void onBackClick() {
                GroupTagInfoActivity.this.finish();
            }

            @Override
            public void onActionClick(int id) {
            }
        });
    }

    @Override
    protected void initUi() {
        findViewById(R.id.tv_add_tag).setOnClickListener(this);
        mListView = (ListView) findViewById(R.id.listView);
        View footer = View.inflate(this, R.layout.grouptag_footer, null);
        footer.findViewById(R.id.rl_footer).setOnClickListener(this);
        mListView.addFooterView(footer);
    }

    @Override
    protected void initAction() {
        mListView.setOnItemClickListener(this);
    }

    @Override
    protected void initData() {

        List<BcyPair> paramsList = new ArrayList<BcyPair>();
        paramsList.add(new BcyPair(HttpUtils.GID, mGid));
        paramsList.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(this).getToken()));

        HashMap<String, String> params = HttpUtils.getData(paramsList);
        Response.Listener<String> onSuccess = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if (StatusCodeUtils.dealStatusCode(response, GroupTagInfoActivity.this, getDataInterface)) {
                    JSONObject result = null;
                    try {
                        result = new JSONObject(response);
                        Gson gson = new Gson();
                        team = gson.fromJson(result.getString(HttpUtils.UPLOAD_DATA), Team.class);
                        team.setIsCreator(team.getIs_creator());
                        processData();
                    } catch (JSONException e) {
                        e.printStackTrace();
                        mProgressbarHelper.onFailed();
                    }

                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
                mProgressbarHelper.onFailed();
            }
        };
        String url = HttpUtils.BASE_URL + GroupApi.getCoretags();
        OnErrorProxy errorProxy = new OnErrorProxy(onError, onSuccess, url, this, null);
        StringRequestParam getUserdataRequest = new StringRequestParam(Request.Method.POST, url, params, onSuccess, errorProxy);
        mQueue.add(getUserdataRequest);
    }

    private void processData() {
        if (null == team)
            return;
        if (TextUtils.isEmpty(team.getId())) {
            if (null == team.getTags() || team.getTags().size() == 0) {
                mProgressbarHelper.onNodata("", true);
                return;
            }
        }

        relaCircle = new ArrayList<>();
        if (!TextUtils.isEmpty(team.getId())) {
            TagDetail workTagDetail = new TagDetail();
            workTagDetail.setType("work");
            workTagDetail.setName(team.getWork());
            workTagDetail.setIntro(team.getIntro());
            workTagDetail.setWid(team.getId());
            workTagDetail.setCover(team.getCover());
            relaCircle.add(workTagDetail);
        }
        if (null != team.getTags()) {
            relaCircle.addAll(team.getTags());
            if (null == mAdapter) {
                mAdapter = new RelatedCircleAdapter(this, relaCircle);
                mListView.setAdapter(mAdapter);
            } else {
                mAdapter.setdata(relaCircle);
                mAdapter.notifyDataSetChanged();
            }
        }
        mProgressbarHelper.onSuccess();
    }

    @Override
    protected void onNetworkError(String result) {
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_add_tag:
                Intent intent = new Intent(GroupTagInfoActivity.this, EditTagActivity.class);
                intent.putExtra(gotoUtil.INTENT_VALUE_ONE, team);
                intent.putExtra(gotoUtil.INTENT_VALUE_TWO, mGid);
                startActivityForResult(intent, GO_EDIT_TAG);
                break;
            case R.id.rl_footer:
                intent = new Intent(this, EditTagActivity.class);
                intent.putExtra(gotoUtil.INTENT_VALUE_ONE, team);
                intent.putExtra(gotoUtil.INTENT_VALUE_TWO, mGid);
                startActivityForResult(intent, GO_EDIT_TAG);
                break;
            default:
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
        if (position < relaCircle.size()) {
            TagDetail tagDetail = relaCircle.get(position);
            if ("work".equals(tagDetail.getType())) {
                Intent intent = new Intent(GroupTagInfoActivity.this, CircleSmoothActivity.class);
                intent.putExtra(gotoUtil.INTENT_VALUE_ONE, tagDetail.getName());
                intent.putExtra(gotoUtil.INTENT_VALUE_TWO, tagDetail.getWid());
                intent.putExtra("from", 2);
                startActivity(intent);
            } else if ("event".equals(tagDetail.getType())) {
                gotoUtil.gotoAct(GroupTagInfoActivity.this, EventDetailActivity.class, tagDetail.getEvent_id());
            } else {
                Intent intent = new Intent(GroupTagInfoActivity.this, CircleTagSmoothActivity.class);
                intent.putExtra(gotoUtil.INTENT_VALUE_ONE, tagDetail.getTag_name());
                intent.putExtra("type", "tag");
                intent.putExtra("from", 2);
                startActivity(intent);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == GO_EDIT_TAG && resultCode == RESULT_OK) {
            team = (Team) data.getSerializableExtra("team");
            processData();
        }
    }
}
